package com.xiao.singleapp.service.impl;

import com.xiao.singleapp.dao.GenCodeDao;
import com.xiao.singleapp.dao.factory.GenCodeDaoFactory;
import com.xiao.singleapp.service.GenCodeService;
import com.xiao.singleapp.utils.GenCodeUtil;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

/**
 * @CreateBy 花和尚  1130365579@qq.com  2023/3/21 15:45
 * @Version 1.0
 */
public class GenCodeServiceImpl implements GenCodeService {

    private GenCodeDao genCodeDao;

    {
        try {
            Configuration config = GenCodeUtil.getGenConfig();
            genCodeDao = GenCodeDaoFactory.getGenCodeDao(config.getString("usingDataBase"));
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<String> listAllTableName() {
        List<Map<String, String>> list = genCodeDao.list();
        ArrayList<String> tableNames = new ArrayList<>();
        list.forEach(map -> {
            tableNames.add(map.get("TABLE_NAME"));
        });
        return tableNames;
    }

    @Override
    public List<Map<String, String>> listAllTabInfo() {
        return genCodeDao.list();
    }

    /**
     * 多表生成代码
     *
     * @param tableNames 表名数组
     * @param packages   模块包名
     * @return
     */
    @Override
    public byte[] generatorCode(String[] tableNames, String packages) {
        ByteArrayOutputStream outs = new ByteArrayOutputStream();
        ZipOutputStream zipOuts = new ZipOutputStream(outs);
        for (String tableName : tableNames) {
            Map<String, String> tableInfo = genCodeDao.listByTableName(tableName);
            List<Map<String, String>> columnsInfo = genCodeDao.listColumns(tableName);
            GenCodeUtil.generatorCode(tableInfo, columnsInfo, zipOuts, packages);
        }
        try {
            zipOuts.flush();
            zipOuts.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outs.toByteArray();
    }
}
